use std::sync::Arc;
use warp::{Filter, Reply, Rejection};
use tracing::{info, error};
use tokio::signal;

use crate::storage::DataStorage;
use crate::api::{
    handlers::ApiHandlers,
    websocket::WebSocketManager,
    models::{QueryParams, HistoryQuery, WriteRequest},
};
use crate::error::{Result, ModbusCollectorError};

/// API服务器
#[derive(Debug)]
pub struct ApiServer {
    storage: DataStorage,
    handlers: Arc<ApiHandlers>,
    websocket_manager: Arc<WebSocketManager>,
    port: u16,
}

impl ApiServer {
    pub async fn new(storage: DataStorage) -> Result<Self> {
        let handlers = Arc::new(ApiHandlers::new(storage.clone()));
        let websocket_manager = Arc::new(WebSocketManager::new());
        
        Ok(Self {
            storage,
            handlers,
            websocket_manager,
            port: 8080, // 可配置
        })
    }
    
    /// 设置写处理器
    pub fn with_write_handler(mut self, write_handler: std::sync::Arc<crate::write_handler::WriteHandler>) -> Self {
        self.handlers = Arc::new(self.handlers.as_ref().clone().with_write_handler(write_handler));
        self
    }
    
    /// 启动API服务器
    pub async fn start(&self) -> Result<()> {
        info!("Starting API server on port {}", self.port);
        
        let cors = warp::cors()
            .allow_any_origin()
            .allow_headers(vec!["content-type", "authorization"])
            .allow_methods(vec!["GET", "POST", "PUT", "DELETE", "OPTIONS"]);
        
        // 创建路由
        let routes = self.create_routes()
            .with(cors)
            .with(warp::log("api"))
            .recover(crate::api::handlers::handle_rejection);
        
        // 启动服务器
        let server = warp::serve(routes)
            .run(([0, 0, 0, 0], self.port));
        
        // 优雅关闭处理
        tokio::select! {
            _ = server => {
                info!("API server stopped");
            },
            _ = signal::ctrl_c() => {
                info!("Received shutdown signal, stopping API server");
            }
        }
        
        Ok(())
    }
    
    /// 创建路由
    fn create_routes(&self) -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone {
        let handlers = self.handlers.clone();
        let ws_manager = self.websocket_manager.clone();
        
        // 健康检查
        let health = warp::path!("health")
            .and(warp::get())
            .and_then(ApiHandlers::health_check);
        
        // 设备相关路由
        let devices = self.device_routes();
        
        // 数据点相关路由
        let points = self.point_routes();
        
        // 系统状态路由
        let system = self.system_routes();
        
        // 写入路由
        let write = self.write_routes();
        
        // WebSocket路由
        let websocket = ws_manager.websocket_filter();
        
        // API路由前缀
        let api_routes = warp::path("api")
            .and(devices.or(points).or(system).or(write));
        
        // 静态文件服务（可选）
        let static_files = warp::path("static")
            .and(warp::fs::dir("./static"))
            .or(warp::path::end().and(warp::fs::file("./static/index.html")));
        
        health
            .or(api_routes)
            .or(websocket)
            .or(static_files)
    }
    
    /// 设备相关路由
    fn device_routes(&self) -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone {
        let handlers = self.handlers.clone();
        
        // GET /api/devices
        let get_devices = warp::path!("devices")
            .and(warp::get())
            .and(warp::query::<QueryParams>())
            .and_then(move |query: QueryParams| {
                let handlers = handlers.clone();
                async move {
                    handlers.get_devices(query).await
                }
            });
        
        // GET /api/devices/{device_id}
        let get_device = warp::path!("devices" / String)
            .and(warp::get())
            .and_then(move |device_id: String| {
                let handlers = handlers.clone();
                async move {
                    handlers.get_device(device_id).await
                }
            });
        
        // GET /api/devices/{device_id}/data
        let get_device_data = warp::path!("devices" / String / "data")
            .and(warp::get())
            .and(warp::query::<QueryParams>())
            .and_then(move |device_id: String, query: QueryParams| {
                let handlers = handlers.clone();
                async move {
                    handlers.get_device_data(device_id, query).await
                }
            });
        
        get_devices.or(get_device).or(get_device_data)
    }
    
    /// 数据点相关路由
    fn point_routes(&self) -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone {
        let handlers = self.handlers.clone();
        
        // GET /api/points
        let get_points = warp::path!("points")
            .and(warp::get())
            .and(warp::query::<QueryParams>())
            .and_then(move |query: QueryParams| {
                let handlers = handlers.clone();
                async move {
                    handlers.get_all_points(query).await
                }
            });
        
        // GET /api/points/{point_id}
        let get_point = warp::path!("points" / String)
            .and(warp::get())
            .and_then(move |point_id: String| {
                let handlers = handlers.clone();
                async move {
                    handlers.get_point(point_id).await
                }
            });
        
        // GET /api/points/{point_id}/history
        let get_point_history = warp::path!("points" / String / "history")
            .and(warp::get())
            .and(warp::query::<HistoryQuery>())
            .and_then(move |point_id: String, query: HistoryQuery| {
                let handlers = handlers.clone();
                async move {
                    handlers.get_point_history(point_id, query).await
                }
            });
        
        get_points.or(get_point).or(get_point_history)
    }
    
    /// 系统状态路由
    fn system_routes(&self) -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone {
        let handlers = self.handlers.clone();
        
        // GET /api/system/status
        let get_status = warp::path!("system" / "status")
            .and(warp::get())
            .and_then(move || {
                let handlers = handlers.clone();
                async move {
                    handlers.get_system_status().await
                }
            });
        
        get_status
    }
    
    /// 写入相关路由
    fn write_routes(&self) -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone {
        let handlers = self.handlers.clone();
        
        // POST /api/write
        let write_point = warp::path!("write")
            .and(warp::post())
            .and(warp::body::json())
            .and_then(move |request: WriteRequest| {
                let handlers = handlers.clone();
                async move {
                    handlers.write_point(request).await
                }
            });
        
        write_point
    }
    
    /// 获取WebSocket管理器
    pub fn websocket_manager(&self) -> Arc<WebSocketManager> {
        self.websocket_manager.clone()
    }
    
    /// 获取服务器端口
    pub fn port(&self) -> u16 {
        self.port
    }
}

impl Clone for ApiServer {
    fn clone(&self) -> Self {
        Self {
            storage: self.storage.clone(),
            handlers: self.handlers.clone(),
            websocket_manager: self.websocket_manager.clone(),
            port: self.port,
        }
    }
}